{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-08-18T14:54:07.535159Z",
     "start_time": "2025-08-18T14:53:54.736952Z"
    }
   },
   "source": [
    "# 创建模型实例\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "chat_model = ChatOpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASH_SCOPE_API_KEY\"), # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model=\"qwen-plus\",\n",
    "    temperature=0.8,\n",
    "    max_tokens=60,\n",
    ")\n",
    "\n",
    "# ------Part 2\n",
    "# 创建一个空的DataFrame用于存储结果\n",
    "import pandas as pd\n",
    "df = pd.DataFrame(columns=[\"flower_type\", \"price\", \"description\", \"reason\"])\n",
    "\n",
    "# 数据准备\n",
    "flowers = [\"玫瑰\", \"百合\", \"康乃馨\"]\n",
    "prices = [\"50\", \"30\", \"20\"]\n",
    "\n",
    "# 定义我们想要接收的数据格式\n",
    "from pydantic import BaseModel, Field\n",
    "class FlowerDescription(BaseModel):\n",
    "    flower_type: str = Field(description=\"鲜花的种类\")\n",
    "    price: int = Field(description=\"鲜花的价格\")\n",
    "    description: str = Field(description=\"鲜花的描述文案\")\n",
    "    reason: str = Field(description=\"为什么要这样写这个文案\")\n",
    "\n",
    "# ------Part 3\n",
    "# 创建输出解析器\n",
    "from langchain.output_parsers import PydanticOutputParser\n",
    "output_parser = PydanticOutputParser(pydantic_object=FlowerDescription)\n",
    "\n",
    "# 获取输出格式指示\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "# 打印提示\n",
    "print(\"输出格式：\",format_instructions)\n",
    "\n",
    "\n",
    "# ------Part 4\n",
    "# 创建提示模板\n",
    "from langchain import PromptTemplate\n",
    "prompt_template = \"\"\"您是一位专业的鲜花店文案撰写员。\n",
    "对于售价为 {price} 元的 {flower} ，您能提供一个吸引人的简短中文描述吗？\n",
    "{format_instructions}\"\"\"\n",
    "\n",
    "# 根据模板创建提示，同时在提示中加入输出解析器的说明\n",
    "prompt = PromptTemplate.from_template(prompt_template, \n",
    "       partial_variables={\"format_instructions\": format_instructions}) \n",
    "\n",
    "# 打印提示\n",
    "print(\"提示：\", prompt)\n",
    "\n",
    "# ------Part 5\n",
    "for flower, price in zip(flowers, prices):\n",
    "    # 根据提示准备模型的输入\n",
    "    input = prompt.format(flower=flower, price=price)\n",
    "    # 打印提示\n",
    "    print(\"提示：\", input)\n",
    "\n",
    "    # 获取模型的输出\n",
    "    output = chat_model.invoke(input)\n",
    "\n",
    "    # 解析模型的输出\n",
    "    parsed_output = output_parser.parse(output.content)\n",
    "    parsed_output_dict = parsed_output.dict()  # 将Pydantic格式转换为字典\n",
    "\n",
    "    # 将解析后的输出添加到DataFrame中\n",
    "    df.loc[len(df)] = parsed_output.dict()\n",
    "\n",
    "# 打印字典\n",
    "print(\"输出的数据：\", df.to_dict(orient='records'))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输出格式： The output should be formatted as a JSON instance that conforms to the JSON schema below.\n",
      "\n",
      "As an example, for the schema {\"properties\": {\"foo\": {\"title\": \"Foo\", \"description\": \"a list of strings\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"foo\"]}\n",
      "the object {\"foo\": [\"bar\", \"baz\"]} is a well-formatted instance of the schema. The object {\"properties\": {\"foo\": [\"bar\", \"baz\"]}} is not well-formatted.\n",
      "\n",
      "Here is the output schema:\n",
      "```\n",
      "{\"properties\": {\"flower_type\": {\"description\": \"鲜花的种类\", \"title\": \"Flower Type\", \"type\": \"string\"}, \"price\": {\"description\": \"鲜花的价格\", \"title\": \"Price\", \"type\": \"integer\"}, \"description\": {\"description\": \"鲜花的描述文案\", \"title\": \"Description\", \"type\": \"string\"}, \"reason\": {\"description\": \"为什么要这样写这个文案\", \"title\": \"Reason\", \"type\": \"string\"}}, \"required\": [\"flower_type\", \"price\", \"description\", \"reason\"]}\n",
      "```\n",
      "提示： input_variables=['flower', 'price'] input_types={} partial_variables={'format_instructions': 'The output should be formatted as a JSON instance that conforms to the JSON schema below.\\n\\nAs an example, for the schema {\"properties\": {\"foo\": {\"title\": \"Foo\", \"description\": \"a list of strings\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"foo\"]}\\nthe object {\"foo\": [\"bar\", \"baz\"]} is a well-formatted instance of the schema. The object {\"properties\": {\"foo\": [\"bar\", \"baz\"]}} is not well-formatted.\\n\\nHere is the output schema:\\n```\\n{\"properties\": {\"flower_type\": {\"description\": \"鲜花的种类\", \"title\": \"Flower Type\", \"type\": \"string\"}, \"price\": {\"description\": \"鲜花的价格\", \"title\": \"Price\", \"type\": \"integer\"}, \"description\": {\"description\": \"鲜花的描述文案\", \"title\": \"Description\", \"type\": \"string\"}, \"reason\": {\"description\": \"为什么要这样写这个文案\", \"title\": \"Reason\", \"type\": \"string\"}}, \"required\": [\"flower_type\", \"price\", \"description\", \"reason\"]}\\n```'} template='您是一位专业的鲜花店文案撰写员。\\n对于售价为 {price} 元的 {flower} ，您能提供一个吸引人的简短中文描述吗？\\n{format_instructions}'\n",
      "提示： 您是一位专业的鲜花店文案撰写员。\n",
      "对于售价为 50 元的 玫瑰 ，您能提供一个吸引人的简短中文描述吗？\n",
      "The output should be formatted as a JSON instance that conforms to the JSON schema below.\n",
      "\n",
      "As an example, for the schema {\"properties\": {\"foo\": {\"title\": \"Foo\", \"description\": \"a list of strings\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"foo\"]}\n",
      "the object {\"foo\": [\"bar\", \"baz\"]} is a well-formatted instance of the schema. The object {\"properties\": {\"foo\": [\"bar\", \"baz\"]}} is not well-formatted.\n",
      "\n",
      "Here is the output schema:\n",
      "```\n",
      "{\"properties\": {\"flower_type\": {\"description\": \"鲜花的种类\", \"title\": \"Flower Type\", \"type\": \"string\"}, \"price\": {\"description\": \"鲜花的价格\", \"title\": \"Price\", \"type\": \"integer\"}, \"description\": {\"description\": \"鲜花的描述文案\", \"title\": \"Description\", \"type\": \"string\"}, \"reason\": {\"description\": \"为什么要这样写这个文案\", \"title\": \"Reason\", \"type\": \"string\"}}, \"required\": [\"flower_type\", \"price\", \"description\", \"reason\"]}\n",
      "```\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:67: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  parsed_output_dict = parsed_output.dict()  # 将Pydantic格式转换为字典\n",
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:70: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  df.loc[len(df)] = parsed_output.dict()\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示： 您是一位专业的鲜花店文案撰写员。\n",
      "对于售价为 30 元的 百合 ，您能提供一个吸引人的简短中文描述吗？\n",
      "The output should be formatted as a JSON instance that conforms to the JSON schema below.\n",
      "\n",
      "As an example, for the schema {\"properties\": {\"foo\": {\"title\": \"Foo\", \"description\": \"a list of strings\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"foo\"]}\n",
      "the object {\"foo\": [\"bar\", \"baz\"]} is a well-formatted instance of the schema. The object {\"properties\": {\"foo\": [\"bar\", \"baz\"]}} is not well-formatted.\n",
      "\n",
      "Here is the output schema:\n",
      "```\n",
      "{\"properties\": {\"flower_type\": {\"description\": \"鲜花的种类\", \"title\": \"Flower Type\", \"type\": \"string\"}, \"price\": {\"description\": \"鲜花的价格\", \"title\": \"Price\", \"type\": \"integer\"}, \"description\": {\"description\": \"鲜花的描述文案\", \"title\": \"Description\", \"type\": \"string\"}, \"reason\": {\"description\": \"为什么要这样写这个文案\", \"title\": \"Reason\", \"type\": \"string\"}}, \"required\": [\"flower_type\", \"price\", \"description\", \"reason\"]}\n",
      "```\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:67: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  parsed_output_dict = parsed_output.dict()  # 将Pydantic格式转换为字典\n",
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:70: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  df.loc[len(df)] = parsed_output.dict()\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示： 您是一位专业的鲜花店文案撰写员。\n",
      "对于售价为 20 元的 康乃馨 ，您能提供一个吸引人的简短中文描述吗？\n",
      "The output should be formatted as a JSON instance that conforms to the JSON schema below.\n",
      "\n",
      "As an example, for the schema {\"properties\": {\"foo\": {\"title\": \"Foo\", \"description\": \"a list of strings\", \"type\": \"array\", \"items\": {\"type\": \"string\"}}}, \"required\": [\"foo\"]}\n",
      "the object {\"foo\": [\"bar\", \"baz\"]} is a well-formatted instance of the schema. The object {\"properties\": {\"foo\": [\"bar\", \"baz\"]}} is not well-formatted.\n",
      "\n",
      "Here is the output schema:\n",
      "```\n",
      "{\"properties\": {\"flower_type\": {\"description\": \"鲜花的种类\", \"title\": \"Flower Type\", \"type\": \"string\"}, \"price\": {\"description\": \"鲜花的价格\", \"title\": \"Price\", \"type\": \"integer\"}, \"description\": {\"description\": \"鲜花的描述文案\", \"title\": \"Description\", \"type\": \"string\"}, \"reason\": {\"description\": \"为什么要这样写这个文案\", \"title\": \"Reason\", \"type\": \"string\"}}, \"required\": [\"flower_type\", \"price\", \"description\", \"reason\"]}\n",
      "```\n",
      "输出的数据： [{'flower_type': '玫瑰', 'price': 50, 'description': '经典玫瑰，绽放纯粹爱意，用一抹嫣红传递你心中的深情告白。', 'reason': '玫瑰是爱情与浪漫的象征，文案通过强调其经典与真挚的情感表达，激发顾客对鲜花背后情感价值的认同，从而提升购买欲望。'}, {'flower_type': '百合', 'price': 30, 'description': '纯洁高雅，如心间绽放的柔光，一束百合，送给你最珍贵的人。', 'reason': '百合象征纯洁与高贵，文案通过情感化的语言唤起购买欲望，同时强调其作为礼物的情感价值，与30元亲民价格形成良好对比，吸引消费者下单。'}, {'flower_type': '康乃馨', 'price': 20, 'description': '温馨满溢，爱在细节中绽放。', 'reason': '康乃馨象征着温暖和细腻的爱，文案强调情感的深度与鲜花的亲民价格，吸引顾客为特别的人挑选这份实惠而有意义的礼物。'}]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:67: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  parsed_output_dict = parsed_output.dict()  # 将Pydantic格式转换为字典\n",
      "C:\\Users\\49247\\AppData\\Local\\Temp\\ipykernel_15972\\177362995.py:70: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  df.loc[len(df)] = parsed_output.dict()\n"
     ]
    }
   ],
   "execution_count": 2
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
